package com.leo.interview;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.atomic.AtomicBoolean;

/**
 *
 * @author xuexiaolei
 * @version 2017年11月06日
 */
public class Interview4_2 {
    private static final int COUNT = 50;
    private static final Object lock = new Object();
    private static AtomicBoolean permit = new AtomicBoolean(true);

    public static void main(String[] args) {
        ExecutorService exec = Executors.newSingleThreadExecutor();
        exec.execute(new Runnable() {
            @Override public void run() {
                for (int i = 0; i < COUNT; i++) {
                    synchronized (lock) {
                        while (!permit.get()) {
                            try {
                                lock.wait();
                            } catch (InterruptedException e) {
                                e.printStackTrace();
                            }

                        }
                        System.out.println("子线程循环十次");
                        permit.set(false);
                        lock.notifyAll();
                    }
                }
                System.out.println("子线程结束");
            }
        });
        for (int i = 0; i < COUNT; i++) {
            synchronized (lock) {
                while (permit.get()) {
                    try {
                        System.out.println("主线程等待");
                        lock.wait();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
                System.out.println("主线程循环一百次");
                permit.set(true);
                lock.notifyAll();
            }
        }
        System.out.println("主线程结束");
        exec.shutdown();
    }
}
